using System.Threading.Tasks;
using JT.WEB.Areas.Identity.Data;
using JTWEB3.Views.Register;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;

namespace JT.WEB.Controllers
{
    public class RegisterController : Controller
    {
        private readonly UserManager<JTWEB3User> _userManager;
        private readonly SignInManager<JTWEB3User> _signInManager;
        public RegisterController(UserManager<JTWEB3User> userManager, SignInManager<JTWEB3User> signInManager)
        {
            _userManager = userManager;
            _signInManager = signInManager;
        }
        public IActionResult Register()
        {
            return View();
        }
        //POST
        [HttpPost]
        public async Task<IActionResult> Register(RegisterModel registerModel)
        {
            if (registerModel is null)
            {
                return View();
            }

            if (ModelState.IsValid)
            {
                JTWEB3User user = new JTWEB3User { UserName = registerModel.Input.Email, Email = registerModel.Input.Email, NickName = registerModel.Input.NickName ?? registerModel.Input.Email, Password = "" };
                IdentityResult result = await _userManager.CreateAsync(user, registerModel.Input.Password).ConfigureAwait(false);
                if (result.Succeeded)
                {
                    IdentityResult a = await _userManager.AddToRoleAsync(user, "JTUsers").ConfigureAwait(false);
                    if (a.Succeeded)
                    {
                        await _signInManager.SignInAsync(user, isPersistent: false);
                        return RedirectToAction(nameof(HomeController.Index), "Home");
                    }
                    foreach (IdentityError i in result.Errors)
                    {
                        ModelState.AddModelError(string.Empty, i.Description);
                    }

                }
                foreach (IdentityError error in result.Errors)
                {
                    if (error.Code == "DuplicateUserName")
                    {
                        ModelState.AddModelError(string.Empty, "用户已存在");
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, error.Description);
                    }
                }
            }
            return View();
        }
    }
}